package com.share.rule.config;

import lombok.extern.slf4j.Slf4j;
import org.kie.api.KieServices;
import org.kie.api.builder.KieBuilder;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.builder.KieModule;
import org.kie.api.runtime.KieContainer;
import org.kie.internal.io.ResourceFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Slf4j
@Configuration
public class DroolsConfig {

    private static final String RULES_CUSTOMER_RULES_DRL = "rules/FeeRule.drl";

    @Bean
    public KieContainer kieContainer() {
        try {
            KieServices kieServices = KieServices.Factory.get();
            KieFileSystem kieFileSystem = kieServices.newKieFileSystem();

            // 加载规则文件
            kieFileSystem.write(ResourceFactory.newClassPathResource(RULES_CUSTOMER_RULES_DRL));

            KieBuilder kieBuilder = kieServices.newKieBuilder(kieFileSystem);
            kieBuilder.buildAll();

            // 检查构建结果
            if (kieBuilder.getResults().hasMessages(org.kie.api.builder.Message.Level.ERROR)) {
                log.error("规则构建错误: {}", kieBuilder.getResults().getMessages());
                throw new RuntimeException("规则构建失败: " + kieBuilder.getResults().getMessages());
            }

            KieModule kieModule = kieBuilder.getKieModule();
            KieContainer container = kieServices.newKieContainer(kieModule.getReleaseId());

            log.info("Drools KieContainer 初始化成功");
            return container;

        } catch (Exception e) {
            log.error("Drools 配置初始化失败", e);
            throw new RuntimeException("Drools 配置初始化失败", e);
        }
    }
}